//
//  TakeFacePhotoViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/15.
//

import UIKit
import RxSwift
import RxCocoa
import AVKit
class TakeFacePhotoViewController: UIViewController {

    @IBOutlet weak var naviBar: NavigationBar!
    
    var product_id = ""
    
    var naviTitle: String = ""
    
    let image = BehaviorRelay<UIImage?>.init(value: nil)
    
    let bag = DisposeBag()
    
    @IBOutlet weak var cardImageView: UIImageView!
    
    var beginDate: Date?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
        // Do any additional setup after loading the view.
    }
    
    private func configView() {
        self.naviBar.backClicked
            .subscribe(onNext: { [weak self] _ in
                self?.navigationController?.popViewController(animated: true)
            })
            .disposed(by: self.bag)
        self.naviBar.title = self.naviTitle
        self.image
            .map { image in
                if (image != nil) {
                    return image!
                } else {
                    return UIImage(named: "loan_take_face_top")!
                }
            }
            .observe(on: MainScheduler.instance)
            .bind(to: self.cardImageView.rx.image)
            .disposed(by: self.bag)
        self.image
            .filter({$0 != nil})
            .subscribe(onNext: { [weak self] image in
                self!.uploadFaceImage(image: image!)
            })
            .disposed(by: self.bag)
    }
    
    private func uploadFaceImage(image: UIImage) {
        Task {
            struct UploadFaceModel: Codable {
                let shrivelled: Int
                let img_url: String
            }
            do {
                self.showLoading(text: nil)
                let data = image.jpegData(compressionQuality: 0.5)!
                let res = try await HTTPManager.default.upload(path: Api.uploadIDCard, data: data, fileKey: "whopper", param: ["cordially": 10, "railings": 1], dataType: UploadFaceModel.self)
                if res.code == 0 {
                    UploadStasticManager.default.uploadRiskPoint(type: 3, beginTime: self.beginDate)
                    self.hideLoading()
                    self.navigationController?.popViewController(animated: true)
                } else {
                    self.hideLoading()
                    self.show(toast: res.state)
                }
            } catch {
                print(error)
                self.hideLoading()
            }
        }
    }

    
    @IBAction func takeFaceAction(_ sender: UIButton) {
        let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
        switch cameraAuthorizationStatus {
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { grant in
                if grant {
                    let imagePicker = UIImagePickerController()
#if DEBUG
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
    imagePicker.sourceType = .photoLibrary
}
#else
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
    imagePicker.sourceType = .camera
}
                    imagePicker.cameraDevice = .front
#endif
                    imagePicker.delegate = self
                    imagePicker.modalPresentationStyle = .overFullScreen
                    self.present(imagePicker, animated: true)
                    if self.beginDate == nil {
                        self.beginDate = Date()
                    }
                } else {
                    let privacyVC = PrivacyEnableViewController()
                    self.alert(viewController: privacyVC)
                }
            }
            break
        case .authorized:
            let imagePicker = UIImagePickerController()
#if DEBUG
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
    imagePicker.sourceType = .photoLibrary
}
#else
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
    imagePicker.sourceType = .camera
}
imagePicker.cameraDevice = .front
#endif
            imagePicker.delegate = self
            imagePicker.modalPresentationStyle = .overFullScreen
            self.present(imagePicker, animated: true)
            if self.beginDate == nil {
                self.beginDate = Date()
            }
            break
        default:
            let privacyVC = PrivacyEnableViewController()
            self.alert(viewController: privacyVC)
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension TakeFacePhotoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info[.originalImage] as? UIImage
        self.image.accept(image)
        picker.dismiss(animated: true)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}
